//
//  ZFAudioRecorder.swift
//  ZFAudioRecorder
//
//  Created by 周正飞 on 2017/11/28.
//  Copyright © 2017年 周正飞. All rights reserved.
//

import UIKit
import AVFoundation
enum ZFRecorderErr: Error {
    case initalRecoderError
}
/// 这是一个刻意为"多段录音"所服务的类. 类似抖音的音频录制版.
class ZFAudioRecorder {
    
    init() {
        settingAudioSession()
    }
    var currentURL:URL?
    
    fileprivate lazy var fileTool = ZFAudioFileTool()
    /// 存放多段录音器的数组
     var recorder :AVAudioRecorder?
    
    fileprivate var recordSettings:[String: Any] = {
        // 2. 设置录音参数
        var recordSettings = [String:Any]()
        recordSettings[AVFormatIDKey] = kAudioFormatMPEG4AAC // 编码格式
        recordSettings[AVSampleRateKey] = 11025.0 // 采样率
        recordSettings[AVNumberOfChannelsKey] = 1 // 通道数
        recordSettings[AVEncoderAudioQualityKey] = kRenderQuality_High // 音频质量
        return recordSettings
    }()
    
    /// 存放各recorder录制的时间段
    var recordersDuration = [TimeInterval]()
 
}

// MARK: - 对外提供的API
extension ZFAudioRecorder {
    /// 开始录音
    func startRecoder() {
        let url = fileTool.createOneStageRecordPath(0);
        self.currentURL = url;
        let recorder = try! AVAudioRecorder(url: url, settings: recordSettings)
        recorder.isMeteringEnabled = true
        self.recorder = recorder
    }
    
    /// 暂停录音
    func pauseRecoder() {
        self.recorder!.pause()
    }
    /// 结束录音
    func endRecoder() {
        // 停止
        recorder!.stop()
        NSLog("RecordUR::" + self.currentURL!.absoluteString)
    }
}
// MARK: - 方法抽取
extension ZFAudioRecorder {
    fileprivate func settingAudioSession() {
        // category参数的含义,options?
        try?AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord)//录音时候允许播放
        try?AVAudioSession.sharedInstance().setActive(true)
    }
}








